<?php
namespace app\weixin\controller;
use think\WeChat;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;
/**
 * 微信响应
 * @author yuqingyong
 */
class Weixin extends Controller
{
    # 公众号appid
    private $appid;
    # 公众号appsecret
    private $appsecret;
    # 微信类
    private $wechat;

    public function __construct()
    {
        parent::__construct();
        # 获取配置
        $config = Db::name('weixin')->where('status',1)->order('id desc')->field('appid,appsecret,mchid,mchkey')->find();
        if($config){
            $this->appid = $config['appid'];
            $this->appsecret = $config['appsecret'];
            $this->wechat = new WeChat($this->appid,$this->appsecret,'yuqingyong','34a92afd66a84ee28653bffd00d3b848');
        }else{
            return json(['status'=>0,'msg'=>'无任何启用的公众号配置']);
        }
    }

    // 消息接口验证
    public function event()
    {
        // $res = $this->wechat->firstValid();
        $this->wechat->responseMsg();
    }

    // 创建菜单接口
    public function createMenue()
    {
        $menu = '{
            "button": [{
                    "type": "click",
                    "name": "发送文本",
                    "key": "V1001_TODAY_TEXT"
                },
                {
                    "name": "发送消息",
                    "sub_button": [{
                            "type": "click",
                            "name": "发送音频",
                            "key": "V1001_TODAY_MUSIC"
                        },
                        {
                            "type": "click",
                            "name": "发送视频",
                            "key": "V1001_TODAY_VIDEO"
                        },
                        {
                            "type": "click",
                            "name": "发送图片",
                            "key": "V1001_TODAY_IMAGE"
                        }
                    ]
                },
                {
                    "name": "其他接口",
                    "sub_button": [{
                            "type": "location_select",
                            "name": "获取地理位置",
                            "key": "V1001_TODAY_WEIZHI"
                        },
                        {
                            "type": "click",
                            "name": "获取二维码",
                            "key": "V1001_TODAY_CODE"
                        },
                        {
                            "type": "click",
                            "name": "发送图文消息",
                            "key": "V1001_TODAY_IMGTEXT"
                        }
                    ]
                }
            ]
        }';
        $res = $this->wechat->menuSet($menu);
        dump($res);die;
    }

    // 上传永久素材 返回素材ID media_id
    public function createPermanentMaterial()
    {
        # 图片文件  返回值：{"media_id":"gS8nt-zzariVoDrgapNQAG2jvKHoogO6i4rmBcze-a4","url":"http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/lQkicCd5cjL1LVnc0bmD85m9OuhbJ3gIGX3weXd3ibNC1z39ibTWPyTvNWkMYcOQPG7ibpb4OPuWiaJcRvLUZux4LVw\/0?wx_fmt=jpeg"}
        // $type = 'image';
        // $file_url = '/ceshi.jpg';

        # 音频文件  返回值：{"media_id":"gS8nt-zzariVoDrgapNQAB74iQLx1n-1xtp9LNjCzVU"}
        // $type = 'voice';
        // $file_url = '/ceshi.mp3';

        # 视频文件  返回值：{"media_id":"gS8nt-zzariVoDrgapNQAMBFcCZdemwvOxNj4MXpDBM"}
        // $type = 'video';
        // $file_url = '/ceshi.mp4';

        # 缩略图文件  返回值：
        $type = 'thumb';
        $file_url = '/ceshi.jpg';
        $result = $this->wechat->addMaterial($type,$file_url);
        dump($result);die;
    }

    // 授权获取用户信息  返回值：{"openid":"oHHjv0mVJeHys1PxpaHYXgN1SafI","nickname":"【亘羽】","sex":1,"language":"zh_CN","city":"南昌","province":"江西","country":"中国","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/NIbRicen6qzm7OcnAB7cQ5ubtEepcWdBFKu7fc7TDrNepGfIlxTkuXgK39spsbo5Docbb8nweeIDFfvHDhOXw3g\/132","privilege":[]}
    public function getUserInfo()
    {
        $res = $this->wechat->getWxUserInfo('http://weixin.yuqingyong.cn/weixin/Weixin/getUserInfo');
        dump($res);die;
    }

    // 发送模板消息  返回值：true or false
    public function sendMsg()
    {
        $data = [
            'username' => array('value'=>'喻庆勇','color'=>'#4876FF'),
            'date' => array('value'=>date('Y-m-d H:i:s'),'color'=>'#743A3A'),
        ];
        $res = $this->wechat->doSendMsg('oHHjv0mVJeHys1PxpaHYXgN1SafI','4qp0SiAM_eDZhrW2royrXQOrdT91209cHU7AL1lo048','http://weixin.yuqingyong.cn',$data);
        dump($res);die;
    }

    // 获取带参数的二维码
    public function getQrCode()
    {
        # 通过ticket获取二维码链接  第一个参数就是携带的参数内容
        $code_url = $this->wechat->getQRCode(1,null,1);
        # 保存的图片名称
        $name = '/upload/code/' . md5($code_url) . '.png';
        # 如果不存在该文件名，则保存到指定位置
        is_file('.' . $name) || file_put_contents('.' . $name, self::curl($code_url));
    }

    // 抓取数据
    private static function curl($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 获取票据
    public function getJsApiTicket()
    {
        # 如果session中保存有效的jsapi_ticket
        if(Session::get('jsapi_ticket_time') > time() && Session::get('jsapi_ticket')){
            $jsapi_ticket = Session::get('jsapi_ticket');
        }else{
            $access_token = $this->wechat->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $result = $this->curl($url);
            $result = json_decode($result,true);
            $jsapi_ticket = $result['ticket'];
            Session::set('jsapi_ticket',$jsapi_ticket);
            Session::set('jsapi_ticket_time',time()+7200);
        }
        return $jsapi_ticket;
    }

    // 获取随机码
    public function getNoncestr($num=8)
    {
        $arr = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'];
        $tmpstr = '';
        $max = count($arr) - 1;
        for($i = 1;$i <= $num;$i++){
            $key = rand(1,$max);
            $tmpstr .= $arr[$key];
        }

        return $tmpstr;
    }

    // 微信js分享
    public function shareWx()
    {
        # 1. 获取jsapi_ticket票据
        $jsapi_ticket = $this->getJsApiTicket();
        $time = time();
        $noncestr = $this->getNoncestr(16);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/weixin/Weixin/shareWx';
        # 2. 获取签名
        $signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$time."&url=".$url."";
        $signature = sha1($signature);

        $assign = [
            'name' => '星辰网络博客[http://www.yuqingyong.cn]',
            'time' => $time,
            'noncestr' => $noncestr,
            'signature' => $signature
        ];
        return $this->fetch('Share/sharewx',$assign);
    }

    // 微信js分享
    public function voice()
    {
        # 1. 获取jsapi_ticket票据
        $jsapi_ticket = $this->getJsApiTicket();
        $time = time();
        $noncestr = $this->getNoncestr(16);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/weixin/Weixin/voice';
        # 2. 获取签名
        $signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$time."&url=".$url."";
        $signature = sha1($signature);

        $assign = [
            'time' => $time,
            'noncestr' => $noncestr,
            'signature' => $signature
        ];
        return $this->fetch('Share/voice',$assign);
    }


}
